package executor;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author tongchen
 * @create 2023-02-11 20:25
 */
public class SemaphoreTest {
   static   private int num=0;
    public static void main(String[] args) throws InterruptedException {

        //创建信号量，即使在多线程，只允许一个线程修改变量，不会产生线程安全问题
        Semaphore semaphore = new Semaphore(1);
        for (int i = 0; i <3 ; i++) {
             Thread t1 =new Thread(()->{
                 for (int j = 0; j <50000 ; j++) {
                     //获取线程
                     try {
                         semaphore.acquire();
                         num++;
                         semaphore.release();
                     } catch (InterruptedException e) {
                         throw new RuntimeException(e);
                     }

                 }
                     });
             t1.start();
        }
        //等待线程执行完
        TimeUnit.SECONDS.sleep(3);
        System.out.println(num);
    }
}
